package serial;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;


public class SerialReader extends Thread {
	private byte[] buffer;
	private InputStream in;
	private ArrayList<SerialReaderListener> listeners;
	private boolean running;

	public SerialReader(InputStream in) {
		this(in, 1024);
	}

	public SerialReader(InputStream in, int bufferSize) {
		this.in = in;
		buffer = new byte[bufferSize];
		listeners = new ArrayList<SerialReaderListener>();
		running = false;
	}

	public void addSerialReaderListener(SerialReaderListener srl) {
		listeners.add(srl);
	}

	public void run() {
		int len = -1;
        try {
        	running = true;
            while ( running && ( len = this.in.read(buffer)) > -1 )  {
            	String input = new String(buffer, 0, len);
            	for (SerialReaderListener srl: listeners) {
            		srl.stringReceived(input);
            	}
            }
            
            //in.close();
            for (SerialReaderListener srl: listeners) {
            	srl.halted();
            }
            
        } catch ( IOException e ) {
        	for (SerialReaderListener srl: listeners) {
        		srl.halted();
        	}
        }
	}
	
	public void halt() {
		running = false;
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

